package com.kxf.androidtestdemo.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.github.cropbitmap.LikeQQCropView;
import com.kxf.androidtestdemo.R;

import java.io.File;

public class CropImageActivity extends BaseActivity {

    private LikeQQCropView likeView;
    private ImageView iv;
    private Uri uri;
    private File cameraSavePath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop_image);

        likeView=findViewById(R.id.likeView);
        iv = findViewById(R.id.iv);
        cameraSavePath = new File(Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
    }

    public void onClickOpenPhoto(View view) {
        goPhotoAlbum();

    }

    public void onClickOpenCamera(View view) {
        goCamera();
    }

    public void onClickCropSuc(View view) {
        Bitmap bmp = likeView.clip();
        likeView.setVisibility(View.GONE);
        iv.setVisibility(View.VISIBLE);
        iv.setImageBitmap(bmp);
    }


    //激活相册操作
    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }

    //激活相机操作
    private void goCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(CropImageActivity.this, "com.kxf.androidtestdemo.fileprovider", cameraSavePath);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        CropImageActivity.this.startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photoPath;
        if (requestCode == 1 && resultCode == RESULT_OK) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                photoPath = cameraSavePath.getPath();
                photoClip(photoPath);
            } else {
                photoPath = uri.getEncodedPath();
                photoClip(uri.getEncodedPath());
            }
            Log.d("拍照返回图片路径:", photoPath);
        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            //判断手机系统版本号
            if (Build.VERSION.SDK_INT >= 19) {
                //4.4及以上系统使用
                photoPath = handleImageOnKitKat(data);
            } else {
                photoPath = handleImageBeforeKitKat(data);
            }
            Log.d("相册返回图片路径:", photoPath);
            photoClip(photoPath);
        }
    }

    @TargetApi(19)
    private String handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        return imagePath;
    }

    private String handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        return imagePath;
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            String orientation = cursor.getString(cursor.getColumnIndex("orientation"));// 获取旋转的角度
            cursor.close();
        }
        return path;
    }

    private void photoClip(String fromFile) {
        likeView.setVisibility(View.VISIBLE);
        iv.setVisibility(View.GONE);

//如果传入的bitmap过大,此方法有OOM的可能
//        likeView.setBitmap(Bitmap bitmap);

//以下方法很安全,做了防止OOM的压缩

/**设置压缩之后的宽和高*/
        likeView.setBitmapForScale(fromFile, 1);

/**[强烈推荐该方法]设置压缩之后的宽度(高度自适应)*/
//        likeView.setBitmapForWidth(param,屏幕宽度或者view宽度);

/**[推荐该方法]设置压缩之后的高度(宽度自适应)*/
//        likeView.setBitmapForHeight(多参);

/**设置压缩的缩放倍数(偶数),图片缩小一半传2,缩小4倍传4*/
//        likeView.setBitmapForScale(多参);
    }


}